package com.pmt.feedplayer.core

import com.pmt.feedplayer.data.PlaybackState
import com.pmt.feedplayer.data.PlaybackProgress
import com.pmt.feedplayer.platform.Player
import com.pmt.feedplayer.platform.createPlayer
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.asStateFlow

/**
 * 播放器管理器
 * 封装平台播放器的具体实现，提供统一的管理接口
 */
class PlayerManager private constructor() {
    private var player: Player? = null
    private val _currentVideoUrl = MutableStateFlow<String?>(null)
    private val _isInitialized = MutableStateFlow(false)
    
    val currentVideoUrl = _currentVideoUrl.asStateFlow()
    val isInitialized = _isInitialized.asStateFlow()
    
    // 委托给平台播放器的状态流
    val playbackStateFlow: Flow<PlaybackState>?
        get() = player?.playbackStateFlow
    
    val progressFlow: Flow<PlaybackProgress>?
        get() = player?.progressFlow
    
    val errorFlow: Flow<String>?
        get() = player?.errorFlow
    
    init {
        initializePlayer()
    }
    
    private fun initializePlayer() {
        try {
            player = createPlayer()
            _isInitialized.value = true
        } catch (e: Exception) {
            _isInitialized.value = false
            // 错误会通过 errorFlow 传递
        }
    }
    
    /**
     * 加载并准备播放视频
     */
    fun loadVideo(url: String) {
        if (_currentVideoUrl.value == url) {
            return // 已经加载了相同的视频
        }
        
        player?.apply {
            setDataSource(url)
            _currentVideoUrl.value = url
        }
    }
    
    /**
     * 开始播放
     */
    fun play() {
        player?.play()
    }
    
    /**
     * 暂停播放
     */
    fun pause() {
        player?.pause()
    }
    
    /**
     * 跳转到指定位置
     */
    fun seekTo(position: Long) {
        player?.seekTo(position)
    }
    
    /**
     * 设置音量
     */
    fun setVolume(volume: Float) {
        player?.setVolume(volume)
    }
    
    /**
     * 获取播放器视图
     */
    fun getPlayerView(): Any? {
        return player?.getPlayerView()
    }
    
    /**
     * 释放播放器资源
     */
    fun release() {
        // 释放播放器资源
        player?.release()
        player = null
        _isInitialized.value = false
        _currentVideoUrl.value = null
    }
    
    companion object {
        @Volatile
        private var instance: PlayerManager? = null
        
        fun getInstance(): PlayerManager {
            return instance ?: synchronized(this) {
                instance ?: PlayerManager().also { instance = it }
            }
        }
    }
}